﻿ using Chloe.Infrastructure.Interception;
using NLog;
using System;
using System.Data;

namespace Kang.DatabaseHelper
{
    public class DbCommandInterceptor : IDbCommandInterceptor
    {
        readonly Logger logger = LogManager.GetCurrentClassLogger();

        /* 执行 DbCommand.ExecuteReader() 时调用 */
        public void ReaderExecuting(IDbCommand command, DbCommandInterceptionContext<IDataReader> interceptionContext)
        {
#if DEBUG
            interceptionContext.DataBag.Add("startTime", DateTime.Now);
#endif
        }
        /* 执行 DbCommand.ExecuteReader() 后调用 */
        public void ReaderExecuted(IDbCommand command, DbCommandInterceptionContext<IDataReader> interceptionContext)
        {
#if DEBUG
            DateTime startTime = (DateTime)(interceptionContext.DataBag["startTime"]);
            logger.Debug($"SQL:{command.CommandText} 执行耗时(毫秒):{DateTime.Now.Subtract(startTime).TotalMilliseconds}");
#endif
        }

        /* 执行 DbCommand.ExecuteNonQuery() 时调用 */
        public void NonQueryExecuting(IDbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
#if DEBUG
            interceptionContext.DataBag.Add("startTime", DateTime.Now);
#endif
        }
        /* 执行 DbCommand.ExecuteNonQuery() 后调用 */
        public void NonQueryExecuted(IDbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
#if DEBUG
            DateTime startTime = (DateTime)(interceptionContext.DataBag["startTime"]);
            logger.Debug($"SQL:{command.CommandText} 执行耗时(毫秒):{DateTime.Now.Subtract(startTime).TotalMilliseconds}");
#endif
        }

        /* 执行 DbCommand.ExecuteScalar() 时调用 */
        public void ScalarExecuting(IDbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
#if DEBUG
            interceptionContext.DataBag.Add("startTime", DateTime.Now);
#endif
        }
        /* 执行 DbCommand.ExecuteScalar() 后调用 */
        public void ScalarExecuted(IDbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
#if DEBUG
            DateTime startTime = (DateTime)(interceptionContext.DataBag["startTime"]);
            logger.Debug($"SQL:{command.CommandText} 执行耗时(毫秒):{DateTime.Now.Subtract(startTime).TotalMilliseconds}");
#endif
        }
    }
}
